package com.suzhe.ymall.product.listener;

import com.suzhe.ymall.common.enums.MessageRoleEnum;
import com.suzhe.ymall.common.enums.TopicEnum;
import com.suzhe.ymall.common.message.OrderSuccessMessage;
import com.suzhe.ymall.product.pojo.MessageLog;
import com.suzhe.ymall.product.service.IMessageLogService;
import com.suzhe.ymall.product.service.ISkuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author suzhe
 * @date 2019/8/13
 */
@Slf4j
@Component
// topic需要和生产者的topic一致，consumerGroup属性是必须指定的，内容可以随意
@RocketMQMessageListener(topic = "ORDER_SUCCESS", consumerGroup = "product-order-success")
public class OrderSuccessListener implements RocketMQListener<OrderSuccessMessage> {

    @Autowired
    ISkuService iSkuService;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Autowired
    IMessageLogService iMessageLogService;

    /**
     *
     * @param  message
     */
    @Override
    public void onMessage(OrderSuccessMessage message) {
        log.info("OrderSuccessListener receive msg：{}", message);
        String messageId = message.getMessageId();
        MessageLog messageLog = iMessageLogService.getById(messageId);
        if (messageLog == null){
            //持久化到本地消息日志表
            messageLog = new MessageLog();
            messageLog.setId(messageId);
            messageLog.setMessageRole(MessageRoleEnum.RECEIVER.value());
            messageLog.setMessageTopic(TopicEnum.ORDER_SUCCESS.value());
            String orderNo = message.getOrderNo();
            messageLog.setMessageBody(orderNo);
            iMessageLogService.save(messageLog);
            //异步处理
            iSkuService.orderSuccess(messageId,orderNo);
        }
    }
}
